package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.meily.web.entity.BehaviorRecords;
import cn.openea.perpartner.meily.web.entity.BehaviorStatistics;
import cn.openea.perpartner.meily.web.entity.Goods;
import cn.openea.perpartner.meily.web.entity.vo.BehaviorStatisticsVo;
import cn.openea.perpartner.meily.web.entity.vo.BehaviorVo;
import cn.openea.perpartner.meily.web.mapper.BehaviorStatisticsMapper;
import cn.openea.perpartner.meily.web.service.IBehaviorRecordsService;
import cn.openea.perpartner.meily.web.service.IBehaviorStatisticsService;
import cn.openea.perpartner.meily.web.service.IGoodsService;
import cn.openea.perpartner.meily.web.service.IOperLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (BehaviorStatistics)表服务实现类
 *
 * @author makejava
 * @since 2023-05-19 10:40:01
 */
@Service("behaviorStatisticsService")
public class BehaviorStatisticsServiceImpl extends ServiceImpl<BehaviorStatisticsMapper, BehaviorStatistics> implements IBehaviorStatisticsService {
    @Resource
    private IBehaviorStatisticsService behaviorStatisticsService;
    @Resource
    private IBehaviorRecordsService behaviorRecordsService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private IOperLogService operLogService;

    /**
     * 通过ID查询单条数据
     *
     * @param behaviorId 主键
     * @return 实例对象
     */
    @Override
    public BehaviorStatistics queryById(String behaviorId) {
        return this.behaviorStatisticsService.queryById(behaviorId);
    }

    /**
     * 更新数据（新增或修改）
     *
     * @param vo 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrEdit(BehaviorVo vo) {

        // 行为编号
        String behaviorId = vo.getBehaviorId();

        // 来源id
        String sourceId = vo.getSourceId();

        // 行为类型。0访问量、1分享量、2分享的点击量
        String behaviorType = vo.getBehaviorType();

        // 分类。0商品、1团购、2样品
        String sourceType = vo.getSourceType();

        // behaviorType = 2，表示来源id是分享id，不能直接更新数据，则需要去行为记录表中获取行为编号
        if("2".equals(behaviorType)){
            LambdaQueryWrapper<BehaviorRecords> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BehaviorRecords::getSourceId, sourceId);
            wrapper.orderByAsc(BehaviorRecords::getCreateTime);
            wrapper.last(" limit 1 ");
            BehaviorRecords behaviorRecords = behaviorRecordsService.getOne(wrapper);
            if(BeanUtil.isEmpty(behaviorRecords)){
                throw new ServiceException("根据来源id获取不到行为编号！");
            }
            behaviorId = behaviorRecords.getBehaviorId();// 行为编号
            sourceType = behaviorRecords.getSourceType();// 分类
            vo.setBehaviorName(behaviorRecords.getBehaviorName());// 行为名称
            vo.setRemark(behaviorRecords.getRemark());// 备注
        }

        // 1.更新行为统计表数据
        BehaviorStatistics behaviorStatistics = getById(behaviorId);
        if(BeanUtil.isEmpty(behaviorStatistics)){
            // 新增
            BehaviorStatistics statistics = new BehaviorStatistics();
            statistics.setBehaviorId(behaviorId);// 行为编号
            statistics.setBehaviorName(vo.getBehaviorName());// 行为名称
            statistics.setBehaviorType(sourceType);// 行为分类（最后更新的行为）
            if("0".equals(behaviorType)){
                statistics.setVisitsVolume(1L);// 访问量+1
            } else if("1".equals(behaviorType)){
                statistics.setShareVolume(1L);// 分享量+1
            } else if("2".equals(behaviorType)){
                statistics.setShareClickVolume(1L);// 分享的点击量+1
            }

            if(baseMapper.insert(statistics) < 0){
                throw new ServiceException("新增行为统计数据出错了！");
            }
        } else {
            // 修改
            if("0".equals(behaviorType)){
                behaviorStatistics.setVisitsVolume(behaviorStatistics.getVisitsVolume() + 1);// 访问量+1
            } else if("1".equals(behaviorType)){
                behaviorStatistics.setShareVolume(behaviorStatistics.getShareVolume() +1);// 分享量+1
            } else if("2".equals(behaviorType)){
                behaviorStatistics.setShareClickVolume(behaviorStatistics.getShareClickVolume() + 1);// 分享的点击量+1
            }
            behaviorStatistics.setBehaviorType(sourceType);// 行为分类（最后更新的行为）
            if(baseMapper.updateById(behaviorStatistics) < 0){
                throw new ServiceException("更新行为统计数据出错了！");
            }
        }

        // 2.新增行为记录
        BehaviorRecords records = new BehaviorRecords();
        records.setBehaviorId(behaviorId);
        records.setBehaviorName(vo.getBehaviorName());
        records.setBehaviorType(behaviorType);
        records.setSourceId(vo.getSourceId());
        records.setSourceType(sourceType);
        records.setCreateUser(vo.getCreateUser());
        records.setCreateUserName(vo.getCreateUserName());
        records.setCreateUserAvatar(vo.getCreateUserAvatar());
        records.setRemark(vo.getRemark());
        if(behaviorRecordsService.insit(records) < 0){
            throw new ServiceException("添加行为记录出错了！");
        }

        return true;
    }

    /**
     * 分页查询
     * @param statistics
     * @return
     */
    @Override
    public List<BehaviorStatistics> findListByVo(BehaviorStatistics statistics) {

        LambdaQueryWrapper<BehaviorStatistics> wrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(statistics.getBehaviorId())){
            wrapper.eq(BehaviorStatistics::getBehaviorId, statistics.getBehaviorId());
        }

        return list(wrapper);
    }

    /**
     * 根据商品编号查询访问量
     * @param goodsNo
     * @return
     */
    @Override
    public BehaviorStatisticsVo queryByGoodsNo(String goodsNo) {
        BehaviorStatisticsVo vo = new BehaviorStatisticsVo();
        // 商品编号
        if(StrUtil.isNotBlank(goodsNo)){
            LambdaQueryWrapper<Goods> goodsWrapper = new LambdaQueryWrapper<>();
            goodsWrapper.eq(Goods::getGoodsNo, goodsNo);
            Goods goods = goodsService.getOne(goodsWrapper);
            if(BeanUtil.isEmpty(goods)){
                return vo;
            }
            BehaviorStatistics statistics = getById(goods.getGoodsId());
            if(BeanUtil.isEmpty(statistics)){
                return vo;
            }
            // 获取访问量
            BeanUtil.copyProperties(statistics, vo);

            // 获取原访问量
            long clickNum = operLogService.queryProductClicks(goodsNo);
            vo.setClickNum(clickNum);
        }
        return vo;
    }

    @Override
    public BehaviorStatisticsVo queryVisitCount(BehaviorStatistics statistics) {
        BehaviorRecords records = behaviorRecordsService.getOne(Wrappers.<BehaviorRecords>lambdaQuery()
                .eq(BehaviorRecords::getBehaviorId, statistics.getBehaviorId()), false);
        if (BeanUtil.isNotEmpty(records)) {
             statistics = getById(records.getBehaviorId());
        }
        BehaviorStatisticsVo statisticsVo = new BehaviorStatisticsVo();
        if (BeanUtil.isNotEmpty(statistics)) {
            BeanUtil.copyProperties(statistics, statisticsVo);
        }
        return statisticsVo;
    }


}
